package com.senbai.springlearning.threadlearn.controller;

import com.senbai.springlearning.threadlearn.bean.OrderQuery;
import com.senbai.springlearning.threadlearn.service.QueryService;
import com.senbai.springlearning.threadlearn.thread.QueryInvoice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.PostConstruct;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.*;

import static java.lang.Thread.sleep;

@Controller
@RequestMapping("/threadlearn")
public class BatchQueryLearn {


    private static volatile ThreadPoolExecutor messageThreadPool = null;

    @Autowired
    QueryService queryService;

    public static ThreadPoolExecutor getMessageThreadPool() {
        if(messageThreadPool == null){
            synchronized (ThreadPoolExecutor.class) {
                if(messageThreadPool == null){
                    /*
                     * 创建固定大小为1的线程池，使用ArrayBlockingQueue阻塞队列，队列大小为1万，线程数超过队列大小时的策略为重试。
                     */
                    messageThreadPool = new ThreadPoolExecutor(1,1,3, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10000),
                            new ThreadPoolExecutor.CallerRunsPolicy());
                }
            }
        }
        return messageThreadPool;
    }

    @RequestMapping(value = "/startBatchSend",method = RequestMethod.POST)
    public String startBatchSend(){
        CountDownLatch cdl = new CountDownLatch(1);
        List<Map<String,Object>> result = new LinkedList<>();
        try {
            for (int i = 0; i < 1000; i++) {
                String orderNo = "1638972";
                orderNo = orderNo + i;
                ThreadPoolExecutor executor = getMessageThreadPool();
                QueryInvoice queryInvoice = new QueryInvoice(orderNo, cdl);
                Future<Map<String, Object>> future = executor.submit(queryInvoice);
                Map<String,Object> queryResult = future.get();
                result.add(queryResult);
            }
        }catch (InterruptedException ie){
                System.out.println(ie.getMessage());
        }catch (ExecutionException ee){
            System.out.println(ee.getMessage());
        }
        return result.toString();

    }
    public static void main(String[] args){

        CountDownLatch cdl = new CountDownLatch(1);
        try {
            for (int i = 0; i < 1000; i++) {
                OrderQuery orderQuery = new OrderQuery();
                String orderNo = "1638972";
                orderNo = orderNo + i;
                String id = UUID.randomUUID().toString();
                CompletableFuture<String> cf = new CompletableFuture<>();
                orderQuery.setOrderNo(orderNo);
                orderQuery.setId(id);
                orderQuery.setCf(cf);

            }
            System.out.println("循环结束");
            cdl.countDown();
            sleep(20000);
        }catch (InterruptedException ie){
            System.out.println(ie.getMessage());
        }

    }




    @PostConstruct
    public void init(){
        //定时任务线程池,创建一个支持定时、周期性或延时任务的限定线程数目(这里传入的是1)的线程池
        //scheduleAtFixedRate是周期性执行 schedule是延迟执行 initialDelay是初始延迟 period是周期间隔 后面是单位
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
//        scheduledExecutorService.scheduleAtFixedRate();

    }
}
